# _*_ coding:utf-8 _*_
# @Time  : 2023.05.04
# @Author: zizlee
from fastapi import APIRouter, Query, Depends
from db_utils import BaseDatabaseConnection
from response import APIResponse
from utils.jwt_token import TokenPayload
from constant import VarietyConstants
from constant.user import UserType
from constant.section_scope import SectionScope
from utils.hutool_utils import SequenceDataUtils


class DatalibVariety:
    GROUPS = {k: v for k, v in VarietyConstants.GROUPS.items() if k not in VarietyConstants.INACTIVE_GROUPS}
    SCOPE = VarietyConstants.SCOPE_DATALIB

    # 所有的分组下的品种
    def group_variety(self, payload: TokenPayload):
        utp = payload.user_type()
        if utp == UserType.REGISTER_USER:  # 注册用户
            return APIResponse.success(data={'data': []})
        with BaseDatabaseConnection() as conn:
            sql = """
                SELECT id,name,code,group_id,price_unit,scope,is_exchange FROM ruizhi_variety
                WHERE is_active=1 AND FIND_IN_SET(%s, scope) ORDER BY sort_num;
            """
            prm = [self.SCOPE]
            conn.cursor.execute(sql, prm)
            v_list = list(conn.cursor.fetchall())
            has_access_list = [v['code'] for v in v_list]
            if utp in UserType.VARIETY_AUTH_SETS:  # 需要验证品种的
                conn.cursor.execute("SELECT id,variety_en FROM ruizhi_user_section_variety WHERE user_id=%s AND sec_key=%s AND expire_date>=CURDATE();",
                                    [payload.user_id(), SectionScope.INDUSTRY_DATALIB_KEY])
                has_access_list = list(conn.cursor.fetchall())
                has_access_list = [v['variety_en'] for v in has_access_list]

        variety_data = []
        for g_key, g_name in self.GROUPS.items():

            g_data = []
            for v in v_list:
                if v['group_id'] == g_key:
                    v['access'] = v['code'] in has_access_list
                    g_data.append(v)

            variety_data.append({
                'key': g_key,
                'name': g_name,
                'varieties': g_data
            })
        res_data = {
            'data': variety_data
        }
        return APIResponse.success(data=res_data)

    # 一个品种下的指标分组
    def index_group(self, variety: str, parent: int):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT id,name,parent_id,vcode FROM datlib_index_group WHERE parent_id=%s AND vcode=%s AND is_active=1
                ORDER BY sort_num;
            """, [parent, variety])
            groups = list(conn.cursor.fetchall())
        res_data = {
            'data': [{**g, 'variety': variety} for g in groups]
        }
        return APIResponse.success(data=res_data)

    # 品种下的指标分组（按tree返回）
    def index_group_tree(self, variety: str):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT id,name,parent_id,vcode FROM datlib_index_group WHERE vcode=%s AND is_active=1
                ORDER BY sort_num;
            """, [variety])
            groups = list(conn.cursor.fetchall())
        ret_tree = SequenceDataUtils.list2tree(data=groups, pkey='parent_id', ckey='id', fvalue=str(0))
        return APIResponse.success(data={'data': ret_tree})

    # 一个品种下的计算分组
    def calculate_group(self, variety: str, parent: int):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT id,name,parent_id FROM calcul_group WHERE parent_id=%s AND vcode=%s AND is_active=1
                ORDER BY sort_num;
            """, [parent, variety])
            groups = list(conn.cursor.fetchall())
        res_data = {
            'data': [{**g, 'variety': variety} for g in groups]
        }
        return APIResponse.success(data=res_data)

    # 品种下的计算分组(tree)
    def calculate_group_tree(self, variety: str):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT id,name,parent_id FROM calcul_group WHERE vcode=%s AND is_active=1
                ORDER BY sort_num;
            """, [variety])
            groups = list(conn.cursor.fetchall())
        ret_tree = SequenceDataUtils.list2tree(data=groups, pkey='parent_id', ckey='id', fvalue=str(0))
        return APIResponse.success(data={'data': ret_tree})

    def primary_index(self, vcode: str):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
              SELECT id,name,is_alone,is_formula,is_stack FROM datlib_group_index WHERE vcode=%s AND is_primary=1 AND is_active=1 LIMIT 1;
           """, [vcode])
        index_list = conn.cursor.fetchone()
        return APIResponse.success(data={'data': index_list})


variety_api = APIRouter()


@variety_api.get('/')
def get_group_variety(payload: TokenPayload = Depends(TokenPayload)):  # 分组下的品种
    return DatalibVariety().group_variety(payload=payload)


@variety_api.get('/indexGroup/')  # 数据指标分组
def get_index_group(variety: str = Query(...), parent: int = Query(0)):
    return DatalibVariety().index_group(variety=variety, parent=parent)


@variety_api.get('/indexGroupTree/')  # 数据指标分组(总)
def get_index_group(variety: str = Query(...)):
    return DatalibVariety().index_group_tree(variety=variety)


@variety_api.get('/formulaGroup/')  # 计算分组
def get_calculation_group(variety: str = Query(...), parent: int = Query(0)):
    return DatalibVariety().calculate_group(variety=variety, parent=parent)


@variety_api.get('/formulaGroupTree/')  # 计算分组
def get_calculation_group(variety: str = Query(...)):
    return DatalibVariety().calculate_group_tree(variety=variety)


@variety_api.get('/primaryIndex/')  # 品种主要指标
def get_variety_primary_index(variety: str = Query(...)):
    return DatalibVariety().primary_index(vcode=variety)